package com.aly.beanValidate.core.validator.impl;

import com.alibaba.fastjson.JSONArray;
import com.aly.beanValidate.core.enums.CAL;
import com.aly.beanValidate.core.FieldDefinition;
import com.aly.beanValidate.core.GlobalConfigs;
import com.aly.beanValidate.core.Util;
import com.aly.beanValidate.core.validator.BaseType;
import com.aly.beanValidate.core.validator.CheckValidator;
import com.aly.beanValidate.core.validator.Name;
import com.aly.beanValidate.i.BeanInfo;
import com.aly.beanValidate.i.FileInfo;
import com.aly.beanValidate.i.FileInfos;
import org.dom4j.Element;

@Name("JsonArrayLen")
public class JsonArrayLenValidator extends CheckValidator {
    private final CAL cal;
    private int len;

    JsonArrayLenValidator(Element element, GlobalConfigs globalConfigs) {
        super(element, globalConfigs);
        len = Integer.valueOf(Util.attr(element, "len"));
        String type = Util.attr(element, "type").toUpperCase();
        cal = CAL.valueOf(type);
    }

    @Override
    public StringBuffer doValidate(FieldDefinition field, Object val, BeanInfo bean, FileInfo fileInfo, FileInfos fileInfos) {
        if (field.getBaseType() == BaseType.JSON) {
            if (val instanceof JSONArray) {
                int size = ((JSONArray) val).size();
                if (!cal.test(size, len)) {
                    return new StringBuffer("数组长度不匹配 实际长度:").append(size).append("条件:").append(cal).append("len:").append(len);
                }
            }
        }
        return null;
    }
}
